﻿Imports System.Threading
Imports System.Windows.Threading

''' <summary>
''' it has its own thread where it executed all the orders
''' </summary>
''' <remarks></remarks>
Public Class MysteryDispacther


    Private theLock As New Object
    Private threadEvent As New AutoResetEvent(False)
    Private otherEvent As New AutoResetEvent(False)
    Private action_to_do As Action
    Private _bg_thread As Thread

    Public Sub New()

        SyncLock theLock
            Dim t As New Thread(AddressOf threadDo)
            t.Name = "the one"
            t.IsBackground = True
            t.Start()
            otherEvent.WaitOne()
        End SyncLock

    End Sub

    Private _actions As New Queue(Of Action)

    Public Sub invoke(act As action)
        If _bg_thread Is Thread.CurrentThread Then 'we are already here avoid recursions
            act.Invoke()
            Exit Sub
        End If
        SyncLock theLock
            action_to_do = act
            threadEvent.Set()
            otherEvent.WaitOne()
            If exception IsNot Nothing Then Throw exception
        End SyncLock
    End Sub

    Private exception As Exception


    Private Sub threadDo()
        _bg_thread = Thread.CurrentThread
        otherEvent.Set()
        While True
            threadEvent.WaitOne()
            exception = Nothing
            Try
                If action_to_do IsNot Nothing Then
                    action_to_do.Invoke()
                End If
            Catch ex As Exception
                exception = ex
            End Try
            otherEvent.Set()
        End While


    End Sub

End Class
